package com.cjkj.equipment.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.cjkj.common.core.constant.*;
import com.cjkj.common.core.domain.R;
import com.cjkj.common.core.exception.ServiceException;
import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.equipment.domain.*;
import com.cjkj.equipment.domain.dto.EquipmentStatusDto;
import com.cjkj.equipment.domain.dto.SmartBraceletDto;
import com.cjkj.equipment.domain.vo.HospitalAreaVo;
import com.cjkj.equipment.mapper.*;
import com.cjkj.equipment.service.ITWarnRecordsService;
import com.cjkj.equipment.service.SmartBraceletDataService;
import com.cjkj.system.api.RemoteHospitalEquipmentService;
import com.cjkj.system.api.domain.APIEquipmentUsageRecords;
import com.cjkj.system.api.domain.APIHospitalEquipment;
import com.cjkj.system.api.domain.APISmartBraceletData;
import com.cjkj.system.api.domain.dto.APIEquipmentStatusDto;
import com.cjkj.system.api.domain.request.BraceletHistoryDataReq;
import com.cjkj.system.api.domain.request.EquipmentHDAReq;
import com.cjkj.system.api.domain.request.LatestDatasReq;
import com.cjkj.system.api.domain.request.PatientEquipmentRTDReq;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Message;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author 93000
 */
@Slf4j
@Service
public class SmartBraceletDataServiceImpl implements SmartBraceletDataService {

    @Resource
    private TEquipmentInfoMapper equipmentInfoMapper;
    @Resource
    private TMedicalConsumablesInfoMapper medicalConsumablesInfoMapper;
    @Resource
    private SmartBraceletDataMapper dataMapper;
    @Resource
    private RemoteHospitalEquipmentService remoteHospitalEquipmentService;
    @Resource
    private TWarnSettingMapper warnSettingMapper;
    @Resource
    private ITWarnRecordsService recordsService;
    @Resource
    private AgentMapper agentMapper;
    @Resource
    private HospitalMapper hospitalMapper;

    @Override
    public void insertData(SmartBraceletData data) {
        dataMapper.insertSmartBraceletData(data);
    }

    @Override
    public void processMessage(Message message) {
        byte[] body;
        try {
            body = message.getBody(byte[].class);
        } catch (Exception e){
            log.error("processMessage occurs error ", e);
            throw new ServiceException("数据采集失败："+e);
        }
        String content = new String(body);
        log.warn(content);
        SmartBraceletDto smartBraceletDto = JSONObject.parseObject(content,SmartBraceletDto.class);
        EquipmentStatusDto equipmentStatusDto = JSONObject.parseObject(content,EquipmentStatusDto.class);
        APIEquipmentStatusDto apiEquipmentStatusDto = new APIEquipmentStatusDto();
        BeanUtils.copyProperties(equipmentStatusDto,apiEquipmentStatusDto);
        SmartBraceletData data = getDataFromDto(smartBraceletDto);

        String equipmentNo = data.getEquipmentNo();
        /* 查询是否系统的设备 */
        TEquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipment(EquipmentConstants.EQUIPMENT_TYPE_SMART_BRACELET_TYPE, equipmentNo);
        if(equipmentInfo == null || EquipmentConstants.EQUIPMENT_ALLOCATION_FLAG_UNALLOTTED.equals(equipmentInfo.getDistributeFlag())) {
            return ;
        }
        /* 判断该设备是否在开单使用 */
        R<APIEquipmentUsageRecords> records = remoteHospitalEquipmentService.getRecordsByEquipment(equipmentNo, SecurityConstants.INNER);
        APIEquipmentUsageRecords useRecord = records.getData();
        if(HttpStatus.SUCCESS != records.getCode() || useRecord == null){
            return ;
        }
        /* 判断传感器耗材是否正确使用 */
        String dataTempSeq = data.getTempSeq();
        if(StringUtils.isNotBlank(dataTempSeq)) {
            String finalStatus = judgmentSensorStatus(data.getAcquisitionTime(), dataTempSeq, data.getPlugStatus(), useRecord.getHospitalId(), useRecord.getVisitNo());
            data.setPlugStatus(finalStatus);
        }
        /* 添加数据 */
        insertData(data);
        /* 报警判断 */
        judgeWarn(data, useRecord);
        // 设备在开单期间的体温数据是否达到15分钟
        temperatureCount(equipmentInfo, useRecord);
        /* 保存使用期间的体温传感器编号数据 */
        if(StringUtils.isNotBlank(dataTempSeq)) {
            saveSensorSeq(useRecord, dataTempSeq);
        }
    }

    /**
     * 判断传感器状态
     * @param acquisitionTime 监测时间
     * @param tempSeq 传感器编号
     * @param plugStatus 当前传感器状态
     * @param hospitalId 医院ID
     * @param visitNo 患者就诊号
     */
    private String judgmentSensorStatus(Date acquisitionTime, String tempSeq, String plugStatus, String hospitalId, Long visitNo){
        TMedicalConsumablesInfo consumablesInfo = medicalConsumablesInfoMapper.selectTMedicalConsumablesInfoByNo(tempSeq);
        if(consumablesInfo == null) {
            // 耗材编号不存在，判定为不合法
            return SensorConstants.SENSOR_STATUS_ILLEGAL;
        } else {
            // 判断是否分配
            if("1".equals(consumablesInfo.getDistributeFlag())) {
                // 如果已分配，则判断使用当前耗材的医院的地址在不在代理商所代理的区域内
                HospitalAreaVo hospitalAreaVo = hospitalMapper.selectHospitalArea(hospitalId);
                if(hospitalAreaVo != null
                        && StringUtils.isNotBlank(hospitalAreaVo.getProvince())
                        && StringUtils.isNotBlank(hospitalAreaVo.getCity())
                        && StringUtils.isNotBlank(hospitalAreaVo.getArea())) {
                    // 只判断设置了地址的医院
                    String agentId = consumablesInfo.getAgentId();
                    int count = agentMapper.selectAgentAreas(agentId, hospitalAreaVo.getProvince(), hospitalAreaVo.getCity(), hospitalAreaVo.getArea());
                    if(count <= 0) {
                        return SensorConstants.SENSOR_STATUS_OUT_OF_AREA;
                    }
                }
            }

            // 是否使用（0-未使用，1-已使用）
            String isUse = consumablesInfo.getIsUse();
            if("0".equals(isUse)) {
                HospitalAreaVo hospitalAreaVo = hospitalMapper.selectHospitalArea(hospitalId);
                int hours = hospitalAreaVo != null && hospitalAreaVo.getBindDuration() != null ? hospitalAreaVo.getBindDuration() : 25;

                consumablesInfo.setIsUse("1");
                consumablesInfo.setVisitNo(visitNo);
                // 使用开始时间
                consumablesInfo.setUseStartTime(acquisitionTime);
                // 有效期
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(acquisitionTime);
                calendar.add(Calendar.HOUR_OF_DAY, hours);
                consumablesInfo.setUseEndTime(calendar.getTime());
                // 保存使用信息
                medicalConsumablesInfoMapper.updateTMedicalConsumablesInfo(consumablesInfo);
            } else {
                if(! visitNo.equals(consumablesInfo.getVisitNo())) {
                    // 已被其他就诊患者使用
                    return SensorConstants.SENSOR_STATUS_USED;
                } else if(! acquisitionTime.before(consumablesInfo.getUseEndTime())) {
                    // 已过有效使用时段
                    return SensorConstants.SENSOR_STATUS_EXPIRED;
                }
            }
        }

        return plugStatus;
    }

    /**
     * 保存就诊患者使用的传感器编号数据
     * @param useRecord 使用记录
     * @param dataTempSeq 传感器编号
     */
    private void saveSensorSeq(APIEquipmentUsageRecords useRecord, String dataTempSeq){
        String sensorSeq = useRecord.getSensorSeq();
        String seqStr = "";
        if(StringUtils.isBlank(sensorSeq)) {
            // 如果该设备没有使用传感器编号数据
            seqStr = dataTempSeq;
        } else {
            if(! sensorSeq.contains(dataTempSeq)) {
                seqStr = sensorSeq + "," + dataTempSeq;
            }
        }

        // 保存数据
        APIEquipmentUsageRecords updateInfo = new APIEquipmentUsageRecords();
        updateInfo.setUseId(useRecord.getUseId());
        updateInfo.setSensorSeq(seqStr);
        remoteHospitalEquipmentService.updateEquipmentUsageRecordStatus(updateInfo, SecurityConstants.INNER);
    }

    @Override
    public List<SmartBraceletData> listData(String equipmentNo, Date startTime, Date endTime) {
        return dataMapper.listData(equipmentNo,startTime,endTime);
    }
    @Override
    public List<SmartBraceletData> listDataBefore(String equipmentNo, Date startTime, Date endTime) {
        return dataMapper.listDataBefore(equipmentNo, startTime, endTime);
    }

    @Override
    public Map<String, Object> appListData(EquipmentHDAReq req) {
        Integer pageNum = req.getPageNum();
        Integer pageSize = req.getPageSize();
        if (pageSize == null || pageNum == null) {
            pageNum = 1;
            pageSize = 25;
        }

        // 查询数据
        PageHelper.startPage(pageNum, pageSize);
        List<SmartBraceletData> smartBraceletData = dataMapper.appListData(req);
        PageInfo<SmartBraceletData> pageInfo = new PageInfo<>(smartBraceletData);

        List<SmartBraceletData> smartBraceletDataList = pageInfo.getList();
        List<APISmartBraceletData> resultList = new ArrayList<>();
        smartBraceletDataList.forEach(e->{
            APISmartBraceletData apiSmartBraceletData = new APISmartBraceletData();
            com.cjkj.common.core.utils.bean.BeanUtils.copyProperties(e,apiSmartBraceletData);
            resultList.add(apiSmartBraceletData);
        });

        Map<String, Object> result = new HashMap<>();
        result.put("data", resultList);
        result.put("total", pageInfo.getTotal());
        return result;
    }

    @Override
    public SmartBraceletData getLastData(PatientEquipmentRTDReq req) {
        return dataMapper.getLastData(req);
    }
    /** 判断异常并记录
     * 1.获取当前全部预警设置；
     * 2.遍历全部设置，并查询该设备得使用记录
     *  a.有人使用，判断是否满足预警条件，满足进行记录；
     *  b.无人使用，直接返回
     * */
    @Override
    public void judgeWarn(SmartBraceletData data, APIEquipmentUsageRecords record){
        if(data == null) {
            return ;
        }
        // 设备号
        String equipmentNo = data.getEquipmentNo();
        // 监测时间
        Date acquisitionTime = data.getAcquisitionTime();
        // 设备开始使用时间
        Date useStartTime = record.getStartTime();

        /*
         * 预警改为连续2条数据在预警范围才进行报警
         */
        int total = 2;
        // 查询该设备前n条数据
        List<SmartBraceletData> braceletDataList = dataMapper.continuousDatas(equipmentNo, useStartTime, acquisitionTime, total);
        if(braceletDataList.size() != total) {
            return ;
        }
        // 查询预警设置
        List<TWarnSetting> warnSettings = warnSettingMapper.selectTWarnSettingList(new TWarnSetting());
        // 查询医院自己设置的预警值
        List<TWarnSetting> hospitalWarnSet = warnSettingMapper.selectHospitalWarnSet(record.getHospitalId(), record.getDeptId());

        // 各种预警值出现的次数
        int spo2LowerCount = 0, spo2UpperCount = 0;
        int heartRateLowerCount = 0, heartRateUpperCount = 0;
        int temperatureLowerCount = 0, temperatureUpperCount = 0;
        int batteryPercentageLowerCount = 0;

        // 遍历监测数据
        for (SmartBraceletData smartBraceletData : braceletDataList) {
            Integer spo2 = smartBraceletData.getSpo2();
            Integer temperature = smartBraceletData.getTemperature();
            Integer heartRate = smartBraceletData.getHeartRate();
            Integer batteryPercentage = smartBraceletData.getBatteryPercentage();

            // 遍历预警设置
            for (TWarnSetting setting : warnSettings) {
                String warnType = setting.getWarnType();
                Double lower = setting.getLowerLimit();
                Double upper = setting.getUpperLimit();

                // 血氧预警
                if(WarnConstants.WARN_TYPE_BRACELET_SPO2.equals(warnType)){
                    List<TWarnSetting> spo2Sets = hospitalWarnSet
                            .stream()
                            .filter(e -> WarnConstants.WARN_TYPE_BRACELET_SPO2.equals(e.getWarnType()))
                            .collect(Collectors.toList());
                    if(!spo2Sets.isEmpty()) {
                        TWarnSetting spo2Set = spo2Sets.get(0);
                        if(spo2Set != null) {
                            lower = spo2Set.getLowerLimit();
                            upper = spo2Set.getUpperLimit();
                        }
                    }

                    if(spo2 != null && spo2 < lower){
                        spo2LowerCount += 1;
                    }
                    if(spo2 != null && spo2 > upper){
                        spo2UpperCount += 1;
                    }
                }
                // 脉率预警
                if(WarnConstants.WARN_TYPE_BPM.equals(warnType)){
                    List<TWarnSetting> hrSets = hospitalWarnSet
                            .stream()
                            .filter(e -> WarnConstants.WARN_TYPE_BPM.equals(e.getWarnType()))
                            .collect(Collectors.toList());
                    if(!hrSets.isEmpty()) {
                        TWarnSetting hrSet = hrSets.get(0);
                        if(hrSet != null) {
                            lower = hrSet.getLowerLimit();
                            upper = hrSet.getUpperLimit();
                        }
                    }

                    if(heartRate != null && heartRate < lower){
                        heartRateLowerCount += 1;
                    }
                    if(heartRate != null && heartRate > upper){
                        heartRateUpperCount += 1;
                    }
                }
                // 体温预警
                if(WarnConstants.WARN_TYPE_TEMPERATURE.equals(warnType)){
                    List<TWarnSetting> tempSets = hospitalWarnSet
                            .stream()
                            .filter(e -> WarnConstants.WARN_TYPE_TEMPERATURE.equals(e.getWarnType()))
                            .collect(Collectors.toList());
                    if(!tempSets.isEmpty()) {
                        TWarnSetting tempSet = tempSets.get(0);
                        if(tempSet != null) {
                            lower = tempSet.getLowerLimit();
                            upper = tempSet.getUpperLimit();
                        }
                    }

                    if(temperature != null && temperature != EquipmentConstants.INITIAL_TEMPERATURE_VALUE
                            && temperature != EquipmentConstants.INVALID_TEMPERATURE2 && (double) temperature / 10 < lower){
                        temperatureLowerCount += 1;
                    }
                    if(temperature != null && temperature != EquipmentConstants.INITIAL_TEMPERATURE_VALUE
                            && temperature != EquipmentConstants.INVALID_TEMPERATURE2 && (double) temperature / 10 > upper){
                        temperatureUpperCount += 1;
                    }
                }
                // 电量预警
                if(WarnConstants.WARN_TYPE_ELECTRIC.equals(warnType)){
                    if(batteryPercentage != null && batteryPercentage <= upper){
                        batteryPercentageLowerCount += 1;
                    }
                }
            }
        }

        SmartBraceletData smartBraceletData = braceletDataList.get(0);
        Integer spo2 = smartBraceletData.getSpo2();
        Integer heartRate = smartBraceletData.getHeartRate();
        Integer temperature = smartBraceletData.getTemperature();
        Integer batteryPercentage = smartBraceletData.getBatteryPercentage();
        // 预警信息
        List<TWarnRecords> warnRecords = new ArrayList<>();

        // 血氧低预警
        String spo2Str = null == spo2 ? "0" : String.valueOf(spo2);
        if(spo2LowerCount == total) {
            TWarnRecords warn = new TWarnRecords();
            warn.setWarnType(WarnConstants.WARN_TYPE_BRACELET_SPO2);
            warn.setWarnContent(WarnConstants.WARN_CONTENT_SPO2_LOW);
            warn.setWarnValue(spo2Str);
            warnRecords.add(warn);
        }
        // 血氧高预警
        if(spo2UpperCount == total) {
            TWarnRecords warn = new TWarnRecords();
            warn.setWarnType(WarnConstants.WARN_TYPE_BRACELET_SPO2);
            warn.setWarnContent(WarnConstants.WARN_CONTENT_SPO2_HIGH);
            warn.setWarnValue(spo2Str);
            warnRecords.add(warn);
        }

        // 脉率低预警
        String heartRateStr = null == heartRate ? "0" : String.valueOf(heartRate);
        if(heartRateLowerCount == total) {
            TWarnRecords warn = new TWarnRecords();
            warn.setWarnType(WarnConstants.WARN_TYPE_BPM);
            warn.setWarnContent(WarnConstants.WARN_CONTENT_BPM_LOW);
            warn.setWarnValue(heartRateStr);
            warnRecords.add(warn);
        }
        // 脉率高预警
        if(heartRateUpperCount == total) {
            TWarnRecords warn = new TWarnRecords();
            warn.setWarnType(WarnConstants.WARN_TYPE_BPM);
            warn.setWarnContent(WarnConstants.WARN_CONTENT_BPM_HIGH);
            warn.setWarnValue(heartRateStr);
            warnRecords.add(warn);
        }

        // 体温低预警
        String tempStr = null == temperature ? "0" : String.valueOf((double) temperature / 10);
        // 体温低预警
        if(temperatureLowerCount == total) {
            TWarnRecords warn = new TWarnRecords();
            warn.setWarnType(WarnConstants.WARN_TYPE_TEMPERATURE);
            warn.setWarnContent(WarnConstants.WARN_CONTENT_TEMPERATURE_LOW);
            warn.setWarnValue(tempStr);
            warnRecords.add(warn);
        }
        // 体温高预警
        if(temperatureUpperCount == total) {
            TWarnRecords warn = new TWarnRecords();
            warn.setWarnType(WarnConstants.WARN_TYPE_TEMPERATURE);
            warn.setWarnContent(WarnConstants.WARN_CONTENT_TEMPERATURE_HIGH);
            warn.setWarnValue(tempStr);
            warnRecords.add(warn);
        }

        // 电量低预警
        String batteryStr = null == batteryPercentage ? "0" : String.valueOf(batteryPercentage);
        if(batteryPercentageLowerCount == total) {
            TWarnRecords warn = new TWarnRecords();
            warn.setWarnType(WarnConstants.WARN_TYPE_ELECTRIC);
            warn.setWarnContent(WarnConstants.WARN_CONTENT_ELECTRIC_LOW);
            warn.setWarnValue(batteryStr);
            warnRecords.add(warn);
        }

        // 如果预警信息不为空
        if(! warnRecords.isEmpty()){
            for (TWarnRecords warn : warnRecords) {
                warn.setHospitalId(record.getHospitalId());
                warn.setDeptId(record.getDeptId());
                warn.setVisitNo(record.getVisitNo());
                warn.setEquipmentNo(equipmentNo);
                warn.setCreateTime(acquisitionTime);
                warn.setHasHandle(WarnConstants.WARN_HANDLE_UNPROCESSED);
                warn.setNextReminderTime(new Date());
            }

            if(!recordsService.saveOrUpdateRecord(warnRecords)){
                log.error("异常记录保存或更新失败"+ equipmentNo + ":" + acquisitionTime);
            }
        }
    }

    private SmartBraceletData getDataFromDto(SmartBraceletDto dto){
        SmartBraceletData data = new SmartBraceletData();
        data.setEquipmentNo(dto.getEquipmentNo());
        data.setProductKey(dto.getProductKey());
        data.setCreateTime(new Date());
        if(dto.getItems().getWearState() != null){
            data.setWearState(dto.getItems().getWearState().getValue());
            data.setAcquisitionTime(dto.getItems().getWearState().getTime());
        }
        if(dto.getItems().getChargeStatus() != null){
            data.setChargeStatus(dto.getItems().getChargeStatus().getValue());
            data.setAcquisitionTime(dto.getItems().getChargeStatus().getTime());
        }
        if(dto.getItems().getBatteryPercentage() != null){
            data.setBatteryPercentage(Integer.parseInt(dto.getItems().getBatteryPercentage().getValue()));
            data.setAcquisitionTime(dto.getItems().getBatteryPercentage().getTime());
        }
        if(dto.getItems().getLowPowerFlag() != null){
            data.setLowPowerFlag(dto.getItems().getLowPowerFlag().getValue());
            data.setAcquisitionTime(dto.getItems().getLowPowerFlag().getTime());
        }
        if(dto.getItems().getOperatingMode() != null){
            data.setOperatingMode(dto.getItems().getOperatingMode().getValue());
            data.setAcquisitionTime(dto.getItems().getOperatingMode().getTime());
        }
        if(dto.getItems().getSpo2() != null){
            data.setSpo2(Integer.parseInt(dto.getItems().getSpo2().getValue()));
            data.setAcquisitionTime(dto.getItems().getSpo2().getTime());
        }
        if(dto.getItems().getFallState() != null){
            data.setFallState(dto.getItems().getFallState().getValue());
            data.setAcquisitionTime(dto.getItems().getFallState().getTime());
        }
        if(dto.getItems().getHeartRate() != null){
            data.setHeartRate(Integer.parseInt(dto.getItems().getHeartRate().getValue()));
            data.setAcquisitionTime(dto.getItems().getHeartRate().getTime());
        }
        if(dto.getItems().getTemperature() != null){
            data.setTemperature(Integer.parseInt(dto.getItems().getTemperature().getValue()));
            data.setAcquisitionTime(dto.getItems().getTemperature().getTime());
        }
        if(dto.getItems().getPlugStatus() != null){
            data.setPlugStatus(dto.getItems().getPlugStatus().getValue());
            data.setAcquisitionTime(dto.getItems().getPlugStatus().getTime());
        }
        if(dto.getItems().getTempSeq() != null){
            data.setTempSeq(dto.getItems().getTempSeq().getValue());
            data.setAcquisitionTime(dto.getItems().getTempSeq().getTime());
        }
        return data;
    }

    private void temperatureCount(TEquipmentInfo equipment, APIEquipmentUsageRecords useRecord) {
        // 如果已经达标，直接返回
        if(EquipmentConstants.SMARTBRACELET_USESTATUS_NORMAL.equals(useRecord.getUseStatus())) {
            return ;
        }
        String equipmentNo = equipment.getEquipmentNo();

        // 1、是否用于测试的设备
        R<APIHospitalEquipment> hospitalEquipmentR = remoteHospitalEquipmentService.getHospitalEquipmentInfo(equipment.getId(), SecurityConstants.INNER);
        APIHospitalEquipment hosEquipment = hospitalEquipmentR.getData();
        if(HttpStatus.SUCCESS == hospitalEquipmentR.getCode() &&
                hosEquipment != null &&
                EquipmentConstants.EQUIPMENT_IS_TEST.equals(hosEquipment.getTestFlag())) {
            // 如果是测试设备，直接修改使用状态为已达标
            APIEquipmentUsageRecords updateInfo = new APIEquipmentUsageRecords();
            updateInfo.setUseId(useRecord.getUseId());
            updateInfo.setEquipmentNo(equipmentNo);
            updateInfo.setUseStatus(EquipmentConstants.SMARTBRACELET_USESTATUS_NORMAL);
            remoteHospitalEquipmentService.updateEquipmentUsageRecordStatus(updateInfo, SecurityConstants.INNER);

            return ;
        }

        /* 2、根据使用记录中开始时间查询监测数据 */
        Date startTime = useRecord.getStartTime();
        Date now = new Date();
        List<SmartBraceletData> smartBraceletData = dataMapper.listData(equipmentNo, startTime, now);
        if(smartBraceletData.isEmpty()) {
            return ;
        }

        /* 3、根据查询的监测数据，筛选出有体温的数据 */
        List<SmartBraceletData> datas = smartBraceletData.stream()
                .filter(e -> e.getTemperature() != null && e.getTemperature() != EquipmentConstants.INITIAL_TEMPERATURE_VALUE
                        && e.getTemperature() != EquipmentConstants.INVALID_TEMPERATURE2 && e.getTemperature() != 0
                        && (StringUtils.isEmpty(e.getPlugStatus()) || SensorConstants.SENSOR_STATUS_LEGAL.equals(e.getPlugStatus())))
                .collect(Collectors.toList());
        // 数据间隔秒数
        long duringTime = 0L;
        if(! datas.isEmpty() && datas.size() >= 2) {
            for (int i = 1; i < smartBraceletData.size(); i++) {
                SmartBraceletData beforeRecord = smartBraceletData.get(i - 1);
                SmartBraceletData nowRecord = smartBraceletData.get(i);

                long times = (nowRecord.getAcquisitionTime().getTime() - beforeRecord.getAcquisitionTime().getTime()) / 1000;
                if(times <= 5 * 60) {
                    // 间隔小于5分钟，则累加
                    duringTime += times;
                }
            }

            /* 5、判断体温数据是否正常上传大于等于十五分钟，如果达标则修改使用记录的达标状态 */
            if (duringTime / 60 >= 15) {
                // 修改使用状态为已达标
                APIEquipmentUsageRecords updateInfo = new APIEquipmentUsageRecords();
                updateInfo.setUseId(useRecord.getUseId());
                updateInfo.setEquipmentNo(equipmentNo);
                updateInfo.setUseStatus(EquipmentConstants.SMARTBRACELET_USESTATUS_NORMAL);
                remoteHospitalEquipmentService.updateEquipmentUsageRecordStatus(updateInfo, SecurityConstants.INNER);
            }
        }
    }

    @Override
    public List<SmartBraceletData> getLatestDatas(LatestDatasReq req) {
        return dataMapper.continuousDatas(req.getEquipmentNo(), req.getStartTime(), req.getEndTime(), req.getTotal());
    }

    @Override
    public Map<String, Object> getBraceletHistoryData(BraceletHistoryDataReq req) {
        Integer pageNum = req.getPageNum();
        Integer pageSize = req.getPageSize();
        if (pageSize == null || pageNum == null) {
            pageNum = 1;
            pageSize = 25;
        }

        // 查询数据
        PageHelper.startPage(pageNum, pageSize);
        List<SmartBraceletData> smartBraceletData = dataMapper.selectBraceletHistoryData(req);
        PageInfo<SmartBraceletData> pageInfo = new PageInfo<>(smartBraceletData);

        List<SmartBraceletData> smartBraceletDataList = pageInfo.getList();
        List<APISmartBraceletData> resultList = new ArrayList<>();
        smartBraceletDataList.forEach( e -> {
            APISmartBraceletData apiSmartBraceletData = new APISmartBraceletData();
            BeanUtils.copyProperties(e, apiSmartBraceletData);
            resultList.add(apiSmartBraceletData);
        });

        Map<String, Object> result = new HashMap<>();
        result.put("data", resultList);
        result.put("total", pageInfo.getTotal());
        return result;
    }
}




